<template>
  <a-card :style="{ width: '480px' }">
    <a-tabs :active-key="formData.loginType" @change="onTabChange">
      <a-tab-pane key="captcha" title="Captcha Login"></a-tab-pane>
      <a-tab-pane key="password" title="Password Login"></a-tab-pane>
    </a-tabs>

    <a-form
      ref="loginFormRef"
      :model="formData"
      class="login-form"
      size="large"
      layout="vertical"
      @submit="handleLogin"
    >
      <a-form-item
        field="email"
        :rules="[{ required: true, message: 'email cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="formData.username" placeholder="test@example.com">
          <template #prefix>
            <icon-email />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        v-if="formData.loginType === 'captcha'"
        field="password"
        :rules="[{ required: true, message: 'code cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="formData.password"
          autocomplete="one-time-code"
          placeholder="code: 012345"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
        <a-button type="primary" class="send" :disabled="countdown > 0" @click="handleSendCaptcha">
          {{ countdown > 0 ? `${countdown}s` : 'send code' }}
        </a-button>
      </a-form-item>
      <a-form-item
        v-else
        field="password"
        :rules="[{ required: true, message: 'password cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="formData.password"
          autocomplete="one-time-code"
          placeholder="input password"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <a-button type="primary" html-type="submit" long :loading="loading"> login </a-button>
        <span v-if="loginError">Login error, refresh and try again</span>
      </a-space>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
  import { ref, reactive, onUnmounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useUserStore } from '@/store/';
  import useLoading from '@/hooks/loading';
  import { LoginData, sendCaptcha } from '@/api/user-api';

  const { loading, setLoading } = useLoading();
  const emit = defineEmits<{ loginSuccess: [user: any]; loginFailed: [error: any] }>();
  const userStore = useUserStore();
  const loginError = ref<boolean>(false);
  const loginFormRef = ref();
  const formData = reactive<LoginData>({ loginType: 'captcha', username: '', password: '' });
  const countdown = ref(0);
  let timer: number | null = null;

  const startCountdown = () => {
    countdown.value = 120;
    timer = window.setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0 && timer) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000);
  };

  const onTabChange = (key) => {
    formData.loginType = key;
  };

  const handleSendCaptcha = async () => {
    if (formData.username === '') {
      loginFormRef.value?.validateField('username');
      return;
    }
    const { result } = await sendCaptcha(formData.username);
    if (result === 1) {
      Message.success(`captcha send to: ${formData.username}`);
      startCountdown();
    } else {
      Message.error(`${formData.username} send captcha failed`);
    }
  };

  const handleLogin = async () => {
    setLoading(true);
    try {
      await loginFormRef.value.validate();
      const user = await userStore.login(formData);
      if (user) {
        formData.username = '';
        formData.password = '';
        emit('loginSuccess', user);
      } else {
        loginError.value = true;
        emit('loginFailed', new Error('Login failed'));
      }
    } catch (error) {
      loginError.value = true;
      emit('loginFailed', error);
    }
    setLoading(false);
  };

  const resetForm = () => {
    formData.username = '';
    formData.password = '';
    countdown.value = 0;
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  /* 离开页面时清理定时器 */
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });

  // 暴露给父组件的方法
  defineExpose({
    resetForm,
    handleLogin,
  });
</script>

<style scoped>
  .login-form {
    padding: 20px 0;
  }

  .btn-send {
    background-image: none;
    background-color: #f1f1f1;
    border-radius: 0;
    color: #333;
    font-weight: normal;
    font-size: 16px;
    height: 46px;
    margin-left: 10px;
  }
</style>

<style>
  .login-form .arco-modal-footer {
    text-align: center;
  }
  .login-form .arco-btn-secondary {
    border-radius: 30px;
    padding: 15px 40px;
    font-size: 20px;
    font-weight: 700;
    min-height: 40px;
  }

  .login-form .arco-btn-primary {
    border-radius: 30px;
    padding: 15px 40px;
    background-color: transparent;
    background-image: linear-gradient(90deg, #df0000 9%, #ffa74c 90%);
    font-size: 20px;
    font-weight: 700;
    min-height: 40px;
  }

  .login-form .send {
    background-image: none;
    background-color: #f1f1f1;
    border-radius: 0;
    color: #333;
    font-weight: normal;
    font-size: 16px;
    margin-left: 10px;
  }
</style>
